package org.learn.phase3.upload;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TCPFileUploadClient {
    public static void main(String[] args) throws Exception {
//1.连接服务器（IP，端口）
        //连接本机的8888端口
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
       //创建读取磁盘文件的输入流
        BufferedInputStream bis = new BufferedInputStream
                (new FileInputStream("d:\\图片\\dog.jpg"));

        byte[] array = streamToByteArray(bis);

        //将array 发送给服务端
        BufferedOutputStream bos = new BufferedOutputStream
                (socket.getOutputStream());
        bos.write(array);//将文件对应的字节数组的内容，写入到数据通道
        bis.close();
        socket.shutdownOutput();//结束标志

        //接收从服务端回复的消息
        InputStream inputStream = socket.getInputStream();
       byte[] buf = new byte[1024];
        int readLine = 0;
        while ((readLine = inputStream.read(buf)) != -1){
            System.out.println(new String(buf,0,readLine));
        }

        //关闭流
        inputStream.close();
        bos.close();
        socket.close();

    }
    //方法
    public static byte[] streamToByteArray(InputStream is) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len ;
        while ((len = is.read(b)) != -1){
            bos.write(b,0,len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }
}
